package com.proj.hot.activity;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.SurfaceView;
import android.view.ViewGroup.LayoutParams;

import java.io.InputStream;

/**
 * 小窗口视频播放器
 */
public class MinVideoView extends SurfaceView {

	private int mContentWidth = 0;
	private int mContentHeight = 0;

	public MinVideoView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public MinVideoView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MinVideoView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int width = getDefaultSize(0, widthMeasureSpec);
		int height = getDefaultSize(0, heightMeasureSpec);
//		Resources resources = this.getResources();
//		DisplayMetrics dm = resources.getDisplayMetrics();
//		int width = dm.widthPixels;
//		int height = dm.heightPixels;
		
		if(width > height) {
			//横屏时拉伸填满屏幕
			setMeasuredDimension(width, height);
		}else{
			int showHeight = mContentWidth>0 ? width * mContentHeight / mContentWidth : width * 9 /16;
			setMeasuredDimension(width, showHeight);
//			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}
	}

	public void setContentSize(int width, int height) {
		this.mContentWidth = width;
		this.mContentHeight = height;
	
		Resources resources = this.getResources();
		DisplayMetrics dm = resources.getDisplayMetrics();
		int sw = dm.widthPixels;  
		int sh = dm.heightPixels;
	
		LayoutParams lp = getLayoutParams();
		if(sw > sh) {
			//横屏时拉伸填满屏幕
			lp.width = sw; 
	        lp.height =sh; 
		}else{
			int showHeight = mContentWidth>0 ? sw * mContentHeight / mContentWidth : sw * 9 /16;
			lp.width = sw; 
	        lp.height =showHeight;
		}
        setLayoutParams(lp);
	}

	public static Bitmap readBitmap(Resources r, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;//之前是ARGB_8888
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		InputStream is = r.openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}
}